package com.uduemc.jcms.common.utils;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.util.DigestUtils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;

public class JcmsCryptoUtil {
	protected static final String DEFAULT_CODING = "utf-8";

	protected static final String CRYPTO_KEY = "jcms.com";

	public static String en(String encrypted) throws Exception {
		return encrypt(encrypted, CRYPTO_KEY);
	}

	public static String de(String encrypted) throws Exception {
		return decrypt(encrypted, CRYPTO_KEY);
	}

	// 解密
	protected static String decrypt(String encrypted, String seed) throws Exception {
		String md5 = DigestUtils.md5DigestAsHex(seed.getBytes(DEFAULT_CODING));
		String md5sub = StrUtil.sub(md5, 0, 16);

		Cipher dcipher = Cipher.getInstance("AES");
		dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(md5sub.getBytes(), "AES"));
		byte[] clearbyte = dcipher.doFinal(Base64.getDecoder().decode(HexUtil.decodeHexStr(encrypted)));
		return new String(clearbyte);
	}

	// 加密
	protected static String encrypt(String content, String seed) throws Exception {
		String md5 = DigestUtils.md5DigestAsHex(seed.getBytes(DEFAULT_CODING));
		String md5sub = StrUtil.sub(md5, 0, 16);

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(md5sub.getBytes(), "AES"));
		byte[] encryptStr = cipher.doFinal(content.getBytes(DEFAULT_CODING));
		return HexUtil.encodeHexStr(Base64.getEncoder().encodeToString(encryptStr), CharsetUtil.CHARSET_UTF_8);
	}

//	public static void main(String[] arges) throws Exception {
//		String str = "2";
//		String en = en(str);
//		System.out.println("加密：" + en);
//		System.out.println("解加密：" + de(en));
//	}

}